/****************************************************************************
 * Included Files
 ****************************************************************************/

#include "pca9538.h"
#include "sdp800.h"
/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/
static uint8_t pca9538_write(uint8_t i_cmd,uint8_t data)
{
	Error error;
	  // write a start condition
	USR_IIC_Start();
	// write the sensor I2C address with the write flag
	error = USR_IIC_Send_Byte((PCA9538_ADDR << 1 | 0x00),1);
	  // write 8 bits of the command
	if(ERROR_NONE == error) {
		error = USR_IIC_Send_Byte(i_cmd,1);
	}
	// write 8 bits of the data to the chip
	if(ERROR_NONE == error) {
	    error = USR_IIC_Send_Byte(data,1);
	}
	USR_IIC_Stop();
	 return error;
}

static uint8_t pca9538_read(uint8_t i_cmd,uint8_t *data)
{
	Error error;
	// write a start condition
	USR_IIC_Start();
	// write I2C address with the write flag
	error = USR_IIC_Send_Byte((PCA9538_ADDR << 1 | 0x00),1);
	// write 8 bits of the command
	if(ERROR_NONE == error) {
		error = USR_IIC_Send_Byte(i_cmd,1);
	}
	// write I2C address with the read flag
	if(ERROR_NONE == error) {
		USR_IIC_Start();
		error = USR_IIC_Send_Byte((PCA9538_ADDR << 1 | 0x01),1);
	}
	if(ERROR_NONE == error){
		*data = USR_IIC_Read_Byte(0);
	}
	USR_IIC_Stop();
	return error;
}
/****************************************************************************
 * Name: pca9538_setbit
 *
 * Description:
 *  Write a bit in a register pair
 *
 ****************************************************************************/
#ifdef NOT_USED
static uint8_t pca9538_setbit(uint8_t pin, uint8_t bitval)
{
	uint8_t buf;
	Error error;

	if (pin > 8)
    {
      return ERROR_IVALID_PARAMETER;
    }

	error = pca9538_read(PCA9538_REG_OUTPUT,&buf);
	if(error == ERROR_NONE)
	{
		if (bitval)
		{
			buf |= (1 << pin);
		}
		else
		{
		    buf &= ~(1 << pin);
		}
		error = pca9538_write(PCA9538_REG_OUTPUT,buf);
	}
	return error;
}
#endif

/****************************************************************************
 * Name: pca9538_getbit
 *
 * Description:
 *  Get a bit from a register pair
 *
 ****************************************************************************/
#ifdef NOT_USED
static int pca9538_getbit( uint8_t pin, uint8_t *val)
{
  uint8_t buf;
  Error error;

  if (pin > 8)
  {
      return -ERROR_IVALID_PARAMETER;
  }
  error = pca9538_read(PCA9538_REG_INPUT,&buf);
  *val = (buf >> pin) & 1;
  return error;
}
#endif

uint8_t pca9538_init(void)
{
	Error error;

	error = pca9538_write(PCA9538_REG_CONFIG,0xFF);//set all pin as input port
	return error;
}
uint8_t pca9538_read_inputdata(uint8_t *data)
{
	uint8_t buf;
	Error error;

	error = pca9538_read(PCA9538_REG_INPUT,&buf);
	if(error == ERROR_NONE)
		*data = buf;
	return error;
}
